package com.breadenglish.cms.api.app.sys.service.impl;

import com.breadenglish.cms.api.app.common.utils.PropertyConfigurerUtils;
import com.breadenglish.cms.api.app.common.utils.StringUtils;
import com.breadenglish.cms.api.app.dao.AudioDao;
import com.breadenglish.cms.api.app.dao.FileDao;
import com.breadenglish.cms.api.app.dao.UseFileDao;
import com.breadenglish.cms.api.app.domain.constants.Constants;
import com.breadenglish.cms.api.app.domain.constants.MessageConstants;
import com.breadenglish.cms.api.app.domain.db.Audio;
import com.breadenglish.cms.api.app.domain.db.UseFile;
import com.breadenglish.cms.api.app.domain.exception.BusinessException;
import com.breadenglish.cms.api.app.domain.model.ResultData;
import com.breadenglish.cms.api.app.domain.query.AudioQuery;
import com.breadenglish.cms.api.app.sys.service.VideoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import sun.misc.BASE64Decoder;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * 作者: guo yao
 * 日期: 2016年01月05日
 * 时间: 下午13:33
 */
@Service("videoService")
public class VideoServiceImpl implements VideoService {


    private static final Logger logger = LoggerFactory.getLogger(VideoServiceImpl.class);

    @Resource
    private FileDao fileDao;

    @Resource
    private AudioDao audioDao;

    @Resource
    private UseFileDao useFileDao;


    @Override
    public void insertVideo(Audio audio, String savePath) throws Throwable {
//        ResultData resultData = new ResultData();
        // 更新file信息
        com.breadenglish.cms.api.app.domain.db.File file = new com.breadenglish.cms.api.app.domain.db.File();
        file = fileDao.selectByPrimaryKey(audio.getVideoId());
        file.setState(Constants.FILE_CLASS_STATE_ACTION);
        fileDao.update(file);
        // 保存图片信息
        String imgFile = audio.getFileDate();
        int index = imgFile.indexOf(",");
        imgFile = imgFile.substring(index + 1);

        Random random = new Random();
        String randomName = "" + random.nextInt(10000) + System.currentTimeMillis() + ".jpg";
        savePath = savePath + File.separator + randomName;
        Long tinyfileId = saveFileImage(randomName, ".jpg");
        base64StringToImage(imgFile, savePath);

        // 保存音频信息
        audio.setCreateTime(new Date());
        if (audio.getState() == Constants.VIDEO_STATE_ACTION) {
            audio.setDeliveryTime(new Date());
        }
        audio.setFileId(tinyfileId);
        audioDao.insert(audio);

        // 保存关系表
        UseFile useFile = new UseFile();
        useFile.setUseId(audio.getAudioId());
        useFile.setFileId(audio.getVideoId());
        useFile.setCreateTime(new Date());
        useFileDao.insert(useFile);
//        resultData.setResultMessage("插入成功!");
//        return resultData;
    }

    @Override
    public void updateVideo(Audio audio, String savePath) throws Throwable {
        AudioQuery oldAudio = audioDao.selectById(audio.getAudioId());
        // 更新file信息
        com.breadenglish.cms.api.app.domain.db.File file = new com.breadenglish.cms.api.app.domain.db.File();
        file = fileDao.selectByPrimaryKey(audio.getVideoId());
        file.setState(Constants.FILE_CLASS_STATE_ACTION);
        fileDao.update(file);
        // 保存图片信息[删除修改前的file]
        Long tinyfileId = -1L;
        if (StringUtils.isNotBlank(audio.getFileDate())) {
            String imgFile = audio.getFileDate();
            int index = imgFile.indexOf(",");
            imgFile = imgFile.substring(index + 1);
            Random random = new Random();
            String randomName = "" + random.nextInt(10000) + System.currentTimeMillis() + ".jpg";
            savePath = savePath + File.separator + randomName;
            tinyfileId = saveFileImage(randomName, ".jpg");
            base64StringToImage(imgFile, savePath);
        }
        // 删除图片
        if (StringUtils.isNotBlank(audio.getFileDate())) {
            com.breadenglish.cms.api.app.domain.db.File file1 = new com.breadenglish.cms.api.app.domain.db.File();
            file1 = fileDao.selectByPrimaryKey(oldAudio.getFileId());
            file1.setDelTag(Constants.YES);
            file1.setUpdateTime(new Date());
            fileDao.update(file1);
        }
        // 更新音频信息
        audio.setUpdateTime(new Date());
        if (audio.getState() == Constants.VIDEO_STATE_ACTION) {
            audio.setDeliveryTime(new Date());
        }
        if (tinyfileId != -1L) {
            audio.setFileId(tinyfileId);
        }
        audioDao.update(audio);
        // 更新关系表
        UseFile oldUseFile = useFileDao.select(new UseFile(oldAudio.getAudioId(), oldAudio.getVideoId())).get(0);
        if (oldUseFile.getFileId() != audio.getVideoId()) {
            UseFile useFile = new UseFile();
            useFile.setUseId(audio.getAudioId());
            useFile.setFileId(audio.getVideoId());
            useFile.setCreateTime(new Date());
            useFileDao.insert(useFile);
            // 删除关系表
            oldUseFile.setDelTag(Constants.YES);
            useFileDao.update(oldUseFile);
        }
        // 删除图片
        /*com.breadenglish.cms.api.app.domain.db.File file1 = new com.breadenglish.cms.api.app.domain.db.File();
        file1 = fileDao.selectByPrimaryKey(oldAudio.getFileId());
        file1.setDelTag(Constants.YES);
        file1.setUpdateTime(new Date());
        fileDao.update(file1);*/


    }


    /**
     * 批量删除
     *
     * @param videoIds
     * @throws Throwable
     */
    @Override
    public void deleteVideo(String videoIds) throws Throwable {
       // TODO 批量删除字符串分隔符 X
        String[] videoId = videoIds.split(":");
        int idLen = videoId.length;
        logger.debug("videoId.length() => " + idLen);
        List<String[]> errors = new ArrayList<String[]>();
        if (idLen == 0) {
            BusinessException businessException = new BusinessException();
            businessException.setCode(MessageConstants.DELETE_CODE_CLASS_UNSELECTED);
            throw businessException;
        }
        int sucNum = 0;
        Audio audio = new Audio();
        audio.setDelTag(Constants.YES);
        audio.setUpdateTime(new Date());

        String[] errorMsg = new String[2];
        // TODO 删除提示信息，采用占位符替换功能 X
        errorMsg[0] = "失败ID: \n";
        for (int i = 0; i < idLen; i++) {
            audio.setAudioId(Long.valueOf(videoId[i]));
            int result = audioDao.update(audio);
            if (result == 0) {
                errorMsg[0] = errorMsg[0] + "  \t " + videoId[i] + "\n";
            }
            sucNum += result;
        }
        if (sucNum != idLen) {
            BusinessException businessException = new BusinessException();
            if (sucNum < idLen && sucNum > 0) {
                errorMsg[1] = "成功删除: " + sucNum + " 条 \n";
            }
            if (sucNum > idLen) {
                errorMsg[1] = "预期删除: " + idLen + " 条, 实际删除: " + sucNum + " 条\n";
            }
            if (sucNum == 0) {
                errorMsg[1] = "\n删除失败";
            }
            errors.add(errorMsg);
            businessException.setKeys(errors);
            businessException.setCode(MessageConstants.DELETE_FAIL);
            throw businessException;
        }
    }

    @Override
    public AudioQuery queryAudioById(Long audioId) throws Throwable {
        return audioDao.selectById(audioId);
    }

    /**
     * 报错图片
     *
     * @param base64String
     * @param savePath
     */
    private static void base64StringToImage(String base64String, String savePath) {
        BASE64Decoder decoder = new sun.misc.BASE64Decoder();
        try {
            byte[] bytes1 = decoder.decodeBuffer(base64String);
            ByteArrayInputStream bais = new ByteArrayInputStream(bytes1);
            BufferedImage bi1 = ImageIO.read(bais);
            // 随机名字
//            Random random = new Random();
//            String randomName = "" + random.nextInt(10000) + System.currentTimeMillis() + ".jpg";
//            File w2 = new File(savePath + File.separator + randomName);
            File w2 = new File(savePath);
            ImageIO.write(bi1, "jpg", w2);
        } catch (IOException e) {
            logger.error("新增音频信息是保存图片失败!");
        }
    }

    /**
     * 保存数据库
     *
     * @param fileName
     * @param extName
     * @return
     */
    private Long saveFileImage(String fileName, String extName) {
        com.breadenglish.cms.api.app.domain.db.File file = new com.breadenglish.cms.api.app.domain.db.File();
        SimpleDateFormat formater = new SimpleDateFormat("yyyyMMdd");
        Long fileId = fileDao.getFileId();
        file.setFileId(fileId);
        file.setFileType(Constants.FILE_TYPE_TINY);
        file.setFileClass(Constants.FILE_CLASS_DEFAULT);
        file.setState(Constants.FILE_CLASS_STATE_ACTION);
        String src = PropertyConfigurerUtils.getProperty(Constants.FILE_SHOW_URL);
//        file.setFileUrl(src + File.separator + formater.format(new Date()) + File.separator + fileName);
        file.setFileUrl(src + formater.format(new Date()) + "/" + fileName);
        file.setFileName(fileName);
        file.setSize(0D);
        file.setExt(extName);
        file.setDelTag(Constants.NOT);
        file.setCreateTime(new Date());
        fileDao.insert(file);
        return fileId;
    }
}
